#include <QDebug>

#include "rsschannel.h"
#include "qrssglobals.h"

RssChannel::RssChannel()
			:RssLeaf()
			, m_getLink(false)
			, m_unreaded(0)
{
}

RssChannel::~RssChannel()
{
	while( !m_itemsList.isEmpty( ))
		delete m_itemsList.takeFirst();
}

void RssChannel::addItem( RssLeaf& item )
{
	m_itemsList.append( &item );
	m_unreaded++;
}

const RssLeaf&	RssChannel::leaf( int ind )
{
	return *m_itemsList[ ind ];
}

void RssChannel::readAll()
{
	foreach( RssLeaf* item, m_itemsList )
		item->setState( eReaded );

	m_unreaded = 0;
}

void RssChannel::externalize( QTextStream& stream )
{
	stream << m_unreaded << ITEMSEPARATOR;	
	stream << m_type << ITEMSEPARATOR;
	stream << m_getLink << ITEMSEPARATOR << "\n";

	RssLeaf::externalize( stream );
	
	if( m_itemsList.count() > 0 )
	{ 
		stream << m_itemsList.count() << ITEMSEPARATOR << "\n";
		QRssLeaves::iterator it = m_itemsList.begin();		
		while( it != m_itemsList.end())
		{
			(*it)->externalize( stream );
			++it;
		}
	}
	else
		stream << 0 << ITEMSEPARATOR << "\n";
}

void RssChannel::internalize( QTextStream& stream )
{
	QString line = stream.readLine();
	QString tmp = getNextItem( line, true );
	m_unreaded = tmp.toInt();
	tmp = getNextItem( line );
	m_type = (QRssFType) tmp.toInt();
	tmp = getNextItem( line );
	m_getLink = (bool) tmp.toInt();

	line = stream.readLine();
	RssLeaf::internalize( line );
	
	line = stream.readLine();
	tmp = getNextItem( line, true );
	int count = tmp.toInt();
	if( count > 0 )
	{
		RssLeaf* leaf;
		for(int i = 0; i < count; ++i )
		{
			line = stream.readLine();
			leaf = new RssLeaf();
			leaf->internalize( line );
			m_itemsList.append( leaf );
		}
	}
}

void RssChannel::setItemState(int ind, ItemState state )
{

	RssLeaf* leaf = m_itemsList.at( ind );
	if( leaf->state() != eReaded && state == eReaded )
	{
		m_unreaded--;
	}
	leaf->setState( state );
}

void RssChannel::setType( QRssFType type )
{
	m_type = type;
}

//EOF
